<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/7/11
 * Time: 16:04
 */

namespace app\common\lib;

use app\common\cachemodel\AppConfig;
use app\common\lib\exception\ApiException;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云OSS文件上传
 * Class AliOss
 * @package app\common\lib
 */
class AliOss
{
    private static $instance;
    private $oss_config;
    private $put_object = 'object'; //将文件写入oss
    private $upload_file = 'file';   //上传文件到oss

    /* 获取数据库oss配置,当然你可以自己写在该类中以变量定义
     * 构造方法为私有防止类被实例化
     */
    private function __construct()
    {
        $oss = (new AppConfig())->configInfo('oss');
        $this->oss_config = [
            'access_key_id' => $oss['access_id'],
            'access_key_secret' => $oss['access_key'],
            'endpoint' => $oss['endpoint'],
            'bucket' => $oss['bucket'],
            'timeout' => $oss['timeout'],
        ];
    }

    /**
     * 克隆方法为私有，防止被克隆
     */
    private function __clone()
    {

    }

    //单例模式
    public static function getInstance()
    {
        if (!self::$instance instanceof AliOss)
        {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 设置config配置
     * @param $type
     * @return mixed
     */
    public function setConfig($type = 'zhunle')
    {
        $config = config('aliyun')[$type];
        $this->oss_config = [
            'access_key_id' => $config['oss_access_id'],
            'access_key_secret' => $config['oss_access_key'],
            'endpoint' => $config['oss_endpoint'],
            'bucket' => $config['oss_bucket'],
            'timeout' => $config['oss_timeout']
        ];
        return self::$instance;
    }

    /**
     * @return array|OssClient
     * 创建oss对象
     */
    public function clientOss()
    {
        if (empty($this->oss_config['access_key_id']) || !isset($this->oss_config['access_key_id']))
        {
            return ['errorMsg' => 'access key id invalid'];
        }
        if (empty($this->oss_config['access_key_secret']) || !isset($this->oss_config['access_key_secret']))
        {
            return ['errorMsg' => 'access key secret invalid'];
        }
        if (empty($this->oss_config['endpoint']) || !isset($this->oss_config['endpoint']))
        {
            return ['errorMsg' => 'endpoint invalid'];
        }
        try
        {
            $oss_client = new OssClient($this->oss_config['access_key_id'], $this->oss_config['access_key_secret'], $this->oss_config['endpoint']);
        }
        catch (OssException $e)
        {
            return ['errorMsg' => $e->getMessage()];
        }
        return $oss_client;
    }

    /**
     * @param $path string oss保存的文件路径（如果没有将会自动创建）
     * @param $file string  文件内容
     * @param $action string 上传类型
     * @return array|bool
     */
    function ossUpload($path, $file, $action = 'object')
    {
        $oss_client = $this->clientOss();

        switch ($action)
        {
            case $this->put_object === $action:
                try
                {
                    $oss_client->putObject($this->oss_config['bucket'], $path, $file);
                }
                catch (OssException $e)
                {
                    return ['errorMsg' => $e->getMessage()];
                }
                return true;
            case $this->upload_file === $action:
                try
                {
                    $oss_client->uploadFile($this->oss_config['bucket'], $path, $file);
                }
                catch (OssException $e)
                {
                    return ['errorMsg' => $e->getMessage()];
                }
                return true;
            default:
        }
        return true;
    }

    /**
     * 设置文件权限私有化
     * @param string $path
     * @return bool
     * @throws OssException
     */
    public function setFileAuthPri($path = '')
    {
        $ossClient = $this->clientOss();
        $auth = 'private'; // private 私有    public-read 公共读    public-read-write公共读写

        $ossClient->putObjectAcl($this->oss_config['bucket'], $path, $auth);

        return true;
    }

    /**
     * 获取授权
     * @param string $path
     * @return string|void
     * @throws ApiException
     */
    public function getAuth($path = '')
    {
        $ossClient = $this->clientOss();
//        $ossClient->setUseSSL(true);
        // 设置URL的有效期为3600秒。
        try
        {
            // 生成GetObject的签名URL。
            $signedUrl = $ossClient->signUrl($this->oss_config['bucket'], $path, $this->oss_config['timeout']);
        }
        catch (OssException $e)
        {
            return '';
        }

        return $signedUrl;
    }

}
